import socket
import json 
import threading
import binascii
import time
from Crypto.Cipher import AES
from Crypto.Util import Padding

HOST = '127.0.0.1' 
PORT = 65432

# 定义加密密钥和初始向量
key = b'\r\xa3ki\t$\n\xab\n\xf7\xf0\xd5?\x9e\xccP'
iv = b'\x8d\x9a\xe7f\x18\xe2Z\xd2x\x11\x1e\x91\xc6\x89d\xb0'

def encode(string):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    # 对字符串进行填充
    padded_string = Padding.pad(string.encode(), AES.block_size,style='pkcs7')
    # 加密填充后的字符串
    encrypted_string = cipher.encrypt(padded_string)
    # 返回加密后的字符串的十六进制表示
    print(binascii.hexlify(encrypted_string).decode())
    return binascii.hexlify(encrypted_string).decode()

def handle_client(conn):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    # 处理单个连接的代码
    data = b''
    while True:
        chunk = conn.recv(4096)
        if not chunk:
            break
        data += chunk
    student_decrypted = cipher.decrypt(data)
    student = Padding.unpad(student_decrypted, AES.block_size,style='pkcs7') 
    student = json.loads(student)
    # print(student)
    id = student['id']
    name = student['name'] 
    print(f"Student name: {name}")  
    print(f"Student id: {id}")
    image_data = binascii.unhexlify(student['image'])
    with open('photo.png', 'wb') as f:
        f.write(image_data)
    time.sleep(3)  # 延迟三秒
    # 加密并发送 hello 消息
    hello_encrypted = encode("hello")
    conn.sendall(hello_encrypted.encode())
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    
    while True:
        conn, addr = s.accept() 
        client_thread = threading.Thread(target=handle_client, args=(conn,))
        client_thread.start()